namespace HZY.Framework.DependencyInjection.Attributes;

/// <summary>
/// 配置文件属性注入
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class AppSettingsAttribute : AopMoAttribute
{
    /// <summary>
    /// 是否读取环境变量
    /// </summary>
    private bool IsReadEnv { get; set; } = false;

    /// <summary>
    /// 配置节点地址地址
    /// </summary>
    private string? Key { get; }

    /// <summary>
    /// 环境变量 对应 key 取 value
    /// </summary>
    private Dictionary<string, string> EnvAndKey { get; } = [];

    /// <summary>
    /// 配置文件属性注入
    /// </summary>
    /// <param name="key"></param>
    public AppSettingsAttribute(string key)
    {
        Key = key;
    }

    /// <summary>
    /// 配置文件属性注入
    /// </summary>
    /// <param name="key"></param>
    /// <param name="isReadEnv"></param>
    public AppSettingsAttribute(string key, bool isReadEnv)
    {
        Key = key;
        IsReadEnv = isReadEnv;
    }

    /// <summary>
    /// 配置文件属性注入
    /// </summary>
    /// <param name="envAndKey"></param>
    public AppSettingsAttribute(Dictionary<string, string> envAndKey)
    {
        EnvAndKey = envAndKey;
        IsReadEnv = true;
    }

    public override void OnSuccess(MethodContext context)
    {
        if (context.ReturnType == null) return;

        var name = context.Method.Name;
        if (!name.StartsWith("get_"))
        {
            return;
        }

        object? result = null;

        if (IsReadEnv)
        {
            // 读取环境变量
            if (!string.IsNullOrWhiteSpace(Key))
            {
                result = Environment.GetEnvironmentVariable(Key);
            }

            if (result is null && EnvAndKey.Count > 0)
            {
                // 读取当前环境
                var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";
                // 根据环境取出 key
                if (EnvAndKey.TryGetValue(env, out var key))
                {
                    result = Environment.GetEnvironmentVariable(key);
                }
            }
        }
        else
        {
            var configuration = AopMoAttribute.WebApplicationBuilder?.Configuration ??
                                this.GetService<IConfiguration>(context)
                ;

            if (string.IsNullOrWhiteSpace(Key))
            {
                return;
            }

            // 读取 configuration
            result = configuration?.GetSection(Key).Get(context.ReturnType);
        }

        if (result is null)
        {
            return;
        }

        context.ReplaceReturnValue(this, result);
    }
}